package com.sky.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * 清理redis缓存
 */
@Slf4j
@Component
@Aspect
public class AutoCleanAspect {
	
	private final StringRedisTemplate redisTemplate;
	
	public AutoCleanAspect(StringRedisTemplate redisTemplate) {this.redisTemplate = redisTemplate;}
	
	@Pointcut("execution(* com.sky.service.impl.*.*(..)) && @annotation(com.sky.annotation.AutoClean)")
	public void autoCleanPointCut() {}
	
	@AfterReturning("autoCleanPointCut()")
	public void autoClean(JoinPoint joinPoint) {
		String className = joinPoint.getTarget().getClass().getName();
		String substring = className.substring(className.lastIndexOf(".") + 1, className.indexOf("ServiceImpl"));
		log.info("删除缓存分类: {}", substring);
		Set<String> keys = redisTemplate.keys(substring + "Cache::*");
		if (keys != null) {
			redisTemplate.delete(keys);
		}
	}
}
